package com.eascs.banknet.boc.service.ftp;

import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.service.BOCAbstractService;
import com.eascs.banknet.boc.vo.FtpFileTemplage;
import com.eascs.banknet.common.entity.LoanUserEntity;
import com.eascs.banknet.constant.FileTypeConstants;
import com.eascs.banknet.log.entity.LogEntity;

@Service("bOCZXBGDownloadService")
public class BOCZXBGDownloadService extends BOCAbstractService {
	private static final Logger logger = LoggerFactory.getLogger(BOCZXBGDownloadService.class);

	@Override
	public Map<String, String> dowork() {
		logger.info("拉取征信报告,跑批开始...");
		List<LoanUserEntity> dataList = loanapplyDao.getPullZXBGDataList();
		if (dataList.isEmpty()) {
			logger.info("拉取征信报告， 没有符合条件的数据");
			return null;
		}
		
		for (LoanUserEntity loanUserEntity : dataList) {
			LogEntity logEntity = initLogData();
			String appno = null;
			try {
				String loanapplyNo = loanUserEntity.getLoanapplyNo();
				appno = loanUserEntity.getBankApplyno();
				String fileType = null;
				if(StringUtils.isBlank(loanUserEntity.getSponsorType())){
					if (StringUtils.isNotBlank(loanUserEntity.getSpouseId())) {
						fileType = FileTypeConstants.DALIST_TYPE_ZXMATE;
					}else{
						fileType = FileTypeConstants.DALIST_TYPE_ZXBGDATA;
					}
				}else if(StringUtils.equalsIgnoreCase(loanUserEntity.getSponsorType(), "D")){
					fileType = FileTypeConstants.DALIST_TYPE_SPONSOR_ZXBG;
				}
				
				FtpFileTemplage ftpFile = bocUtil.getBocFtpFileTemplate(fileType);
				boolean saveResult = bocNetService.getFtpAttachment(ftpFile, appno, loanapplyNo, null);
				if (!saveResult) {
					logger.error("拉取征信报告失败， appno:[{}], loanapplyNo:[{}], fileType:[{}]", appno, loanapplyNo, fileType);
					logService.writeLog(logEntity, appno, LogEntity.RESULT_TYPE_ERROR, null);
				} else {
					logger.error("拉取征信报告成功， appno:[{}], loanapplyNo:[{}], fileType:[{}]", appno, loanapplyNo, fileType);
					logService.writeLog(logEntity, appno, LogEntity.RESULT_TYPE_SUCCESS, null);
				}
			} catch (Exception e) {
				logger.error("拉取征信报告出现异常， appno:[{}], errMsg：[{}]", appno, e);
			}
		}
		logger.info("拉取征信报告,跑批结束...");
		return null;
	}

	@Override
	public LogEntity initLogData() {
		LogEntity logEntity = new LogEntity();
		logEntity.setBankType(LogEntity.BANK_TYPE_BOC);
		logEntity.setTransType("ZXBG");
		logEntity.setTypeName("征信报告");
		logEntity.setStartTime(new Date());
		return logEntity;
	}
}
